package org.xfy.ymcc.service.impl;

import cn.hutool.Hutool;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.xfy.common.constant.BusinessKey;
import org.xfy.common.exception.GlobalException;
import org.xfy.common.result.JsonResult;
import org.xfy.common.util.AssertUtil;
import org.xfy.common.util.StrUtils;
import org.xfy.ymcc.dto.SendSmsDto;
import org.xfy.ymcc.service.IVerifycodeService;

import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public JsonResult imageCode(String imageCodeKey) {
        AssertUtil.isTrue(StringUtils.hasText(imageCodeKey),"图片验证码不能为空");
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(300, 100, 4, 4);
        String code = captcha.getCode();
        redisTemplate.opsForValue().set(imageCodeKey,code,2, TimeUnit.MINUTES);
        return JsonResult.success().setData(captcha.getImageBase64());
    }

    @Override
    public JsonResult sendSmsCode(SendSmsDto sendSmsDto) {
        //校验
        AssertUtil.isTrue(redisTemplate.hasKey(sendSmsDto.getKey()),"图片验证码已过期");
        String code = redisTemplate.opsForValue().get(sendSmsDto.getKey()).toString();
        AssertUtil.isTrue(sendSmsDto.getImageCode().equals(code),"图片验证码不匹配");
        //生成手机验证码
        String randomString = StrUtils.getRandomString(6);
        String phoneKey=sendSmsDto.getMobile()+ BusinessKey.SEGMENTATION+BusinessKey.REGISTER_SMS_CODE_SUFFIX;
        if(redisTemplate.hasKey(phoneKey)){
            //获取key的过期时间
            Long expire = redisTemplate.getExpire(phoneKey, TimeUnit.SECONDS);
            if(expire>120){
                throw new GlobalException("操作太频繁,请稍后重试");
            }
            //小于2分钟就发送原来的验证码
            String OldKey = redisTemplate.opsForValue().get(phoneKey).toString();
            randomString=OldKey;
        }
        //存入Redis
        redisTemplate.opsForValue().set(phoneKey,randomString,3,TimeUnit.MINUTES);
        //发送短信
        System.out.println(randomString);
        return JsonResult.success();
    }
}
